<template>
  <div class="file-tools">
    <ToolContainer
      tool-name="文件处理"
      default-tab="convert"
      @tab-change="handleTabChange"
    >
      <template #tabs>
        <!-- 格式转换标签页 -->
        <el-tab-pane label="格式转换" name="convert">
          <ToolSection
            show-upload
            upload-text="拖拽文件到此处或点击上传"
            upload-tip="支持多种文件格式转换"
            :upload-icon="UploadFilled"
            @file-change="handleFileChange"
          >
            <template #preview>
              <div v-if="fileName" class="file-preview">
                <div class="file-info">
                  <p><strong>文件名：</strong>{{ fileName }}</p>
                  <p><strong>文件大小：</strong>{{ fileSize }}</p>
                </div>
              </div>
            </template>

            <template #options>
              <div v-if="fileName" class="convert-options">
                <el-form label-width="100px">
                  <el-form-item label="目标格式">
                    <el-select v-model="targetFormat" placeholder="选择目标格式">
                      <el-option label="PDF" value="pdf" />
                      <el-option label="DOCX" value="docx" />
                      <el-option label="TXT" value="txt" />
                      <el-option label="HTML" value="html" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleConvert" 
                :loading="loading"
                :disabled="!fileName"
              >
                转换
              </el-button>
              <el-button 
                type="success" 
                @click="handleDownload" 
                :loading="loading"
                :disabled="!fileName"
              >
                下载
              </el-button>
            </template>
          </ToolSection>
        </el-tab-pane>
        
        <!-- 压缩解压标签页 -->
        <el-tab-pane label="压缩解压" name="compress">
          <ToolSection
            show-upload
            upload-text="拖拽文件到此处或点击上传"
            upload-tip="支持ZIP、RAR、7Z等格式"
            :upload-icon="UploadFilled"
            @file-change="handleFileChange"
          >
            <template #preview>
              <div v-if="fileName" class="file-preview">
                <div class="file-info">
                  <p><strong>文件名：</strong>{{ fileName }}</p>
                  <p><strong>文件大小：</strong>{{ fileSize }}</p>
                </div>
              </div>
            </template>

            <template #options>
              <div v-if="fileName" class="compress-options">
                <el-form label-width="100px">
                  <el-form-item label="压缩格式">
                    <el-select v-model="compressFormat" placeholder="选择压缩格式">
                      <el-option label="ZIP" value="zip" />
                      <el-option label="RAR" value="rar" />
                      <el-option label="7Z" value="7z" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="压缩级别">
                    <el-slider
                      v-model="compressLevel"
                      :min="1"
                      :max="9"
                      :step="1"
                      show-input
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleCompress" 
                :loading="loading"
                :disabled="!fileName"
              >
                压缩
              </el-button>
              <el-button 
                type="success" 
                @click="handleExtract" 
                :loading="loading"
                :disabled="!fileName"
              >
                解压
              </el-button>
            </template>
          </ToolSection>
        </el-tab-pane>
        
        <!-- 批量重命名标签页 -->
        <el-tab-pane label="批量重命名" name="rename">
          <ToolSection
            show-upload
            upload-text="拖拽文件到此处或点击上传"
            upload-tip="支持批量文件重命名"
            :upload-icon="UploadFilled"
            :multiple="true"
            :show-file-list="true"
            @file-change="handleFilesChange"
          >
            <template #options>
              <div v-if="fileList.length > 0" class="rename-options">
                <el-form label-width="100px">
                  <el-form-item label="文件前缀">
                    <el-input v-model="prefix" placeholder="文件名前缀" />
                  </el-form-item>
                  <el-form-item label="文件后缀">
                    <el-input v-model="suffix" placeholder="文件名后缀" />
                  </el-form-item>
                  <el-form-item label="起始编号">
                    <el-input-number v-model="startNumber" :min="1" placeholder="起始编号" />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleRename" 
                :loading="loading"
                :disabled="fileList.length === 0"
              >
                重命名
              </el-button>
              <el-button 
                type="success" 
                @click="handleDownload" 
                :loading="loading"
                :disabled="fileList.length === 0"
              >
                下载
              </el-button>
            </template>
          </ToolSection>
        </el-tab-pane>
      </template>
    </ToolContainer>

    <!-- 功能介绍组件 -->
    <FeatureIntro
      :title="featureConfig.title"
      :description="featureConfig.description"
      :header-icon="featureConfig.headerIcon"
      :features="featureConfig.features"
      :initial-visible="showIntro"
      @close="showIntro = false"
    />
  </div>
</template>

<script>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import JSZip from 'jszip'
import ToolContainer from '@/components/ToolContainer.vue'
import ToolSection from '@/components/ToolSection.vue'
import FeatureIntro from '@/components/FeatureIntro.vue'
import { featuresConfig } from '@/config/featuresConfig.js'

export default {
  name: 'FileTools',
  components: {
    UploadFilled,
    ToolContainer,
    ToolSection,
    FeatureIntro
  },
  setup() {
    const loading = ref(false)
    const fileName = ref('')
    const fileSize = ref('')
    const targetFormat = ref('pdf')
    const compressFormat = ref('zip')
    const compressLevel = ref(6)
    const fileList = ref([])
    const prefix = ref('')
    const suffix = ref('')
    const startNumber = ref(1)
    const currentFile = ref(null)
    const showIntro = ref(true)

    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const handleTabChange = (tabName) => {
      console.log('切换到标签页:', tabName)
    }

    const handleFileChange = (file) => {
      if (!file) return
      fileName.value = file.name
      fileSize.value = formatFileSize(file.raw.size)
      currentFile.value = file.raw
    }

    const handleFilesChange = (files) => {
      fileList.value = files.map(file => ({
        name: file.name,
        size: formatFileSize(file.raw.size),
        raw: file.raw
      }))
    }

    const handleConvert = async () => {
      if (!fileName.value || !currentFile.value) {
        ElMessage.warning('请先上传文件')
        return
      }
      loading.value = true
      
      try {
        const convertedFile = await convertFile(currentFile.value, targetFormat.value)
        downloadFile(convertedFile, fileName.value.replace(/\.[^.]+$/, `.${targetFormat.value}`))
        loading.value = false
        ElMessage.success('转换完成')
      } catch (error) {
        loading.value = false
        ElMessage.error('转换失败：' + error.message)
      }
    }

    const handleCompress = async () => {
      if (!fileName.value || !currentFile.value) {
        ElMessage.warning('请先上传文件')
        return
      }
      loading.value = true
      
      try {
        const compressedFile = await compressFile(currentFile.value, compressFormat.value, compressLevel.value)
        downloadFile(compressedFile, fileName.value + '.' + compressFormat.value)
        loading.value = false
        ElMessage.success('压缩完成')
      } catch (error) {
        loading.value = false
        ElMessage.error('压缩失败：' + error.message)
      }
    }

    const handleExtract = async () => {
      if (!fileName.value || !currentFile.value) {
        ElMessage.warning('请先上传文件')
        return
      }
      loading.value = true
      
      try {
        const extractedFiles = await extractFile(currentFile.value)
        // 创建一个包含所有解压文件的zip
        const zip = new JSZip()
        extractedFiles.forEach((file, index) => {
          zip.file(`extracted_${index + 1}.txt`, file)
        })
        const zipBlob = await zip.generateAsync({ type: 'blob' })
        downloadFile(zipBlob, 'extracted_files.zip')
        loading.value = false
        ElMessage.success('解压完成')
      } catch (error) {
        loading.value = false
        ElMessage.error('解压失败：' + error.message)
      }
    }

    const handleRename = async () => {
      if (fileList.value.length === 0) {
        ElMessage.warning('请先上传文件')
        return
      }
      loading.value = true
      
      try {
        const zip = new JSZip()
        fileList.value.forEach((file, index) => {
          const newName = generateNewFileName(file.name, index)
          zip.file(newName, file.raw)
        })
        const zipBlob = await zip.generateAsync({ type: 'blob' })
        downloadFile(zipBlob, 'renamed_files.zip')
        loading.value = false
        ElMessage.success('重命名完成')
      } catch (error) {
        loading.value = false
        ElMessage.error('重命名失败：' + error.message)
      }
    }

    const handleDownload = () => {
      if (!fileName.value && fileList.value.length === 0) {
        ElMessage.warning('请先处理文件')
        return
      }
      ElMessage.success('请使用具体功能按钮进行下载')
    }

    // 文件格式转换函数
    async function convertFile(file, targetFormat) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => {
          try {
            const content = e.target?.result
            let convertedContent = content
            
            // 简单的文本格式转换示例
            if (targetFormat === 'txt') {
              convertedContent = content.replace(/<[^>]*>/g, '') // 移除HTML标签
            } else if (targetFormat === 'json') {
              try {
                const lines = content.split('\n').filter(line => line.trim())
                const jsonData = { lines }
                convertedContent = JSON.stringify(jsonData, null, 2)
              } catch {
                convertedContent = JSON.stringify({ content }, null, 2)
              }
            } else if (targetFormat === 'csv') {
              const lines = content.split('\n')
              convertedContent = lines.map(line => `"${line.replace(/"/g, '""')}"`).join('\n')
            }
            
            const blob = new Blob([convertedContent], { type: 'text/plain' })
            resolve(blob)
          } catch (error) {
            reject(error)
          }
        }
        reader.onerror = () => reject(new Error('文件读取失败'))
        reader.readAsText(file)
      })
    }

    // 文件压缩函数
    async function compressFile(file, format, level) {
      const zip = new JSZip()
      zip.file(file.name, file)
      
      const compressionLevel = level === 1 ? 1 : level === 2 ? 6 : 9
      return await zip.generateAsync({ 
        type: 'blob',
        compression: 'DEFLATE',
        compressionOptions: { level: compressionLevel }
      })
    }

    // 文件解压函数
    async function extractFile(file) {
      try {
        const zip = new JSZip()
        const zipContent = await zip.loadAsync(file)
        const files = []
        
        for (const [filename, zipEntry] of Object.entries(zipContent.files)) {
          if (!zipEntry.dir) {
            const content = await zipEntry.async('text')
            files.push(content)
          }
        }
        
        return files
      } catch (error) {
        throw new Error('不是有效的压缩文件')
      }
    }

    // 生成新文件名
    function generateNewFileName(originalName, index) {
      const extension = originalName.substring(originalName.lastIndexOf('.'))
      const baseName = originalName.substring(0, originalName.lastIndexOf('.'))
      
      let newName = ''
      if (prefix.value) {
        newName += prefix.value
      }
      
      newName += (startNumber.value + index).toString().padStart(3, '0')
      
      if (suffix.value) {
        newName += suffix.value
      }
      
      return newName + extension
    }

    // 下载文件
    function downloadFile(blob, filename) {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }

    return {
      loading,
      fileName,
      fileSize,
      targetFormat,
      compressFormat,
      compressLevel,
      fileList,
      prefix,
      suffix,
      startNumber,
      showIntro,
      featureConfig: featuresConfig.fileTools,
      UploadFilled,
      handleTabChange,
      handleFileChange,
      handleFilesChange,
      handleConvert,
      handleCompress,
      handleExtract,
      handleRename,
      handleDownload
    }
  }
}
</script>

<style scoped>
.file-tools {
  position: relative;
}

.file-preview {
  width: 100%;
}

.file-info {
  padding: 16px;
  background: var(--el-bg-color-page, #fafbfc);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter, #f2f6fc);
}

.file-info p {
  margin: 8px 0;
  color: var(--el-text-color-primary, #303133);
}

.convert-options,
.compress-options,
.rename-options {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .file-info {
    padding: 12px;
  }
}
</style> 